"""
日志管理模块
负责读取、解析和过滤代理服务器日志
"""
import os
import re
import logging
from datetime import datetime

# 配置日志
logger = logging.getLogger(__name__)


class LogManager:
    def __init__(self, log_file='proxy_server.log'):
        self.log_file = log_file
        logger.info(f"初始化日志管理器，日志文件: {log_file}")
    
    def parse_log_line(self, line):
        """解析单行日志"""
        line = line.strip()
        if not line:
            return None
        
        # 匹配不同格式的日志
        patterns = [
            # 格式1: 2025-06-22 15:45:55 INFO: 启动代理服务器 0.0.0.0:8080
            (r'^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) (\w+): (.+)$', 'standard'),
            # 格式2: [15:45:55.359] 加载了 3 条代理规则
            (r'^\[(\d{2}:\d{2}:\d{2}\.\d+)\] (.+)$', 'mitmproxy'),
            # 格式3: 127.0.0.1:56481: GET http://127.0.0.1:31001/xxx
            (r'^(\d+\.\d+\.\d+\.\d+:\d+): (.+)$', 'request'),
            # 格式4:  << [Errno 61] Connect call failed
            (r'^ << (.+)$', 'error'),
        ]
        
        for pattern, log_type in patterns:
            match = re.match(pattern, line)
            if match:
                if log_type == 'standard':
                    return {
                        'timestamp': match.group(1),
                        'level': match.group(2),
                        'message': match.group(3),
                        'type': log_type
                    }
                elif log_type == 'mitmproxy':
                    # 转换时间格式
                    time_str = match.group(1)
                    today = datetime.now().strftime('%Y-%m-%d')
                    timestamp = f"{today} {time_str.split('.')[0]}"
                    return {
                        'timestamp': timestamp,
                        'level': 'INFO',
                        'message': match.group(2),
                        'type': log_type
                    }
                elif log_type == 'request':
                    today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    return {
                        'timestamp': today,
                        'level': 'DEBUG',
                        'message': f"[{match.group(1)}] {match.group(2)}",
                        'type': log_type
                    }
                elif log_type == 'error':
                    today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    return {
                        'timestamp': today,
                        'level': 'ERROR',
                        'message': match.group(1),
                        'type': log_type
                    }
        
        # 如果都不匹配，作为普通信息处理
        today = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        return {
            'timestamp': today,
            'level': 'INFO',
            'message': line,
            'type': 'unknown'
        }
    
    def read_logs(self, rule_filter=None, level_filter=None, date_filter=None, limit=500):
        """读取并过滤日志"""
        logs = []
        
        if not os.path.exists(self.log_file):
            return logs
        
        try:
            with open(self.log_file, 'r', encoding='utf-8') as f:
                lines = f.readlines()
            
            # 解析日志行
            for line in lines:
                log_entry = self.parse_log_line(line)
                if log_entry:
                    logs.append(log_entry)
            
            # 应用过滤器
            filtered_logs = []
            for log in logs:
                # 规则过滤
                if rule_filter and rule_filter not in log['message']:
                    continue
                
                # 级别过滤
                if level_filter and log['level'] != level_filter:
                    continue
                
                # 日期过滤
                if date_filter:
                    try:
                        log_date = log['timestamp'].split(' ')[0]
                        if log_date != date_filter:
                            continue
                    except:
                        continue
                
                filtered_logs.append(log)
            
            # 限制数量并倒序（最新的在前）
            return filtered_logs[-limit:][::-1]
            
        except Exception as e:
            print(f"读取日志失败: {e}")
            return []